import './GoodsRecommendCom.less'
import { useModel } from '@umijs/max'
import { Button, Form, Typography, App, Popconfirm, Drawer, Space, Alert, Image, Spin } from 'antd'
import FlipMove from 'react-flip-move'
import { useEffect, useState, forwardRef, useImperativeHandle, useRef } from 'react'
import { ProTable } from '@ant-design/pro-components'
import styles from './GoodsRecommendCom.less'

function GoodsRecommendCom({}, ref) {
  const { message } = App.useApp()

  const { goodsList, setGoodsList, DynamicPageData, couponList, currentTab } = useModel('ActivityEditor')
  const { GetPlatformGoodsList, GetShopSelections } = useModel('Goods')

  const [oldDragItem, setOldDragItem] = useState() // 当前拖拽对象
  const [newDragItem, setNewDragItem] = useState() // 拖拽交换对象
  const [isEnter, setIsEnter] = useState() // 是否拖拽进行
  const [isActive, setIsActive] = useState() // 是否拖拽

  const [goodsDrawer, setGoodsDrawer] = useState(false) // 选择商品抽屉
  const [goodsDrawerLoading, setGoodsDrawerLoading] = useState(false) // 选择商品抽屉 loading
  const [drawerSelectGoods, setDrawerSelectGoods] = useState([]) // 选择的商品
  const [addGoodsPageSize, setAddGoodsPageSize] = useState(5) //  每页数量
  const [shopList, setShopList] = useState([]) // 店铺列表
  const selectGoodsTableRef = useRef() // 选择商品表格ref
  let cancelRowKeys = [] // 取消选择的项目

  // 开关商品抽屉
  const triggerGoodsDrawer = () => {
    setGoodsDrawer(!goodsDrawer)
  }

  // 处理商品抽屉选择商品
  const handleDisplay = async () => {
    if (!drawerSelectGoods.length) {
      message.warning('请最少选择一个商品')
      return
    }

    setGoodsDrawerLoading(true)
    // 动态计算价格
    let params = {
      goodsList: drawerSelectGoods.map(i => ({ id: i.id })),
      couponList: couponList.map(i => ({ id: i.id }))
    }

    const res = await DynamicPageData(params)

    if (res) {
      const newGoodsList = res.goodsList.map(item => {
        return {
          ...item,
          link: `/pages/index/goodsDetails/goodsDetails?id=${item.id}`
        }
      })

      setGoodsDrawerLoading(false)

      setGoodsList([...newGoodsList])
      setDrawerSelectGoods([])
      triggerGoodsDrawer()
    }
  }

  //  获取店铺列表
  const getShopList = async () => {
    const res = await GetShopSelections()
    res && setShopList(res.map(i => [i.id, i.shop_name]))
  }

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  /* 拖拽开始 */
  const onDragStart = value => {
    setOldDragItem(value)
    setIsActive(value.id)
  }

  /* 拖拽进行 */
  const onDragEnter = value => {
    setIsEnter(value.id)
    setNewDragItem(value)
  }

  /* 拖拽结束 */
  const onDragEnd = () => {
    if (oldDragItem !== newDragItem) {
      const oldIndex = goodsList.indexOf(oldDragItem) //获取当前对象所在数组坐标
      const newIndex = goodsList.indexOf(newDragItem) //获取当前目标对象所在数组坐标
      const newArray = [...goodsList]
      newArray.splice(oldIndex, 1) //删除老节点
      newArray.splice(newIndex, 0, oldDragItem) //增加新节点
      setGoodsList(newArray) //保存拖拽后的数组
      setIsActive(-1) //重置状态
      setIsEnter(-1)
    }
  }

  useEffect(() => {
    document.addEventListener('dragover', function (event) {
      //阻止事件的默认行为
      event.preventDefault()
      //设置拖拽时鼠标样式
      event.dataTransfer.dropEffect = 'move'
    })
  }, [])

  // 新增
  const handleAddGoods = () => {
    if (goodsList.length >= 30) {
      message.error('最多添加30个')
      return
    }

    triggerGoodsDrawer()
    if (goodsList && goodsList.length) {
      setDrawerSelectGoods(goodsList)
    }
  }

  // 删除
  const handleRemoveGoods = item => {
    const newArray = goodsList.filter(v => v.id !== item.id)
    setGoodsList(newArray)
  }

  // 获取提交数据
  const handleFinish = () => {
    let params = {
      goodsList
    }

    return params
  }

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    handleFinish
  }))

  const selectGoodsColumns = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200,
      render: (text, record) => (
        <Space>
          <Image width={48} src={record.goods_cover_url} />
          <a onClick={() => goProduct(3, record.id, record.merchant_id)}>{text}</a>
        </Space>
      )
    },
    {
      title: '商品ID',
      dataIndex: 'id',
      width: 60,
      hideInTable: true
    },
    {
      title: '买断价',
      dataIndex: 'buyout_price_range',
      hideInSearch: true,
      width: 140
    },
    {
      title: '状态',
      dataIndex: 'is_display',
      valueEnum: {
        0: { text: '未展示', status: 'Warning' },
        1: { text: '已上架', status: 'Success' },
        2: { text: '未展示', status: 'Warning' }
      },
      valueType: 'select',
      width: 140
    },
    {
      title: '租赁信息',
      dataIndex: 'rent_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('rent')) {
          const { deposit, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                押金：{deposit[0]}~{deposit[1]}
              </div>
              <div>
                租期：{periods[0]}~{periods[1]}
              </div>
              <div>
                期数：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                每期租金：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '买卖信息',
      dataIndex: 'buy_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('buy')) {
          const { first_pay_range, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                首付款：{first_pay_range[0]}~{first_pay_range[1]}
              </div>
              <div>
                尾期：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                期数：{periods[0]}~{periods[1]}
              </div>
              <div>
                每期尾款：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '物流配送',
      dataIndex: 'delivery_type_names',
      width: 120,
      hideInSearch: true,
      render: text => (
        <>
          {text.map(i => (
            <div key={i} className={styles.delivery_name}>
              {i}
            </div>
          ))}
        </>
      )
    },
    {
      title: '归属店铺',
      dataIndex: 'merchant_id',
      valueType: 'select',
      valueEnum: new Map(shopList),
      width: 120
    },
    {
      title: '提交时间',
      dataIndex: 'create_time',
      hideInSearch: true,
      width: 220
    },
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return (
          <a
            key='check'
            onClick={() => {
              goProduct(3, row.id, row.merchant_id)
            }}
          >
            详情
          </a>
        )
      }
    }
  ]

  return (
    <div className='goods_com'>
      <div className='goods_title'>
        已选择商品{goodsList.length}个<span>拖拽可排序</span>
      </div>

      <FlipMove duration={200} easing='ease-out' className='goods_list'>
        {goodsList.map(item => (
          <div
            className={
              oldDragItem === item && isActive === item.id
                ? 'goods_active goods_item'
                : newDragItem === item && isEnter === item.id
                ? 'goods_enter goods_item'
                : 'goods_item'
            }
            draggable={true}
            onDragStart={() => {
              onDragStart(item)
            }}
            onDragEnter={() => {
              onDragEnter(item)
            }}
            onDragEnd={() => {
              onDragEnd()
            }}
            key={item.id}
          >
            <img className='goods_img' src={item.img} alt='商品' />
            <Popconfirm title='确认删除吗?' onConfirm={() => handleRemoveGoods(item)} okText='确认' cancelText='取消'>
              <div className='goods_delete'>-</div>
            </Popconfirm>
          </div>
        ))}
      </FlipMove>

      <Button style={{ marginTop: '20px' }} block size='large' type='dashed' onClick={() => handleAddGoods()}>
        选择商品({goodsList.length}/30)
      </Button>

      {/*选择商品抽屉*/}
      <Drawer
        title='选择商品'
        placement='right'
        className={styles.goods_drawer_wrapper}
        onClose={triggerGoodsDrawer}
        open={goodsDrawer}
        width={980}
        destroyOnClose
        footer={
          <div className={styles.drawer_footer}>
            <Space>
              <Button disabled={!drawerSelectGoods.length} onClick={triggerGoodsDrawer}>
                取消
              </Button>
              <Button type='primary' disabled={!drawerSelectGoods.length} onClick={handleDisplay}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div className='drawer_content'>
          {goodsDrawerLoading && (
            <div className='drawer_loading'>
              <Spin></Spin>
              <p>数据处理中...</p>
            </div>
          )}

          <Alert message='仅可以选择已上架的商品，最多选择30个' type='info' showIcon />
          <ProTable
            search={{
              defaultCollapsed: false,
              labelWidth: 75,
              span: 6
            }}
            actionRef={selectGoodsTableRef}
            tableAlertOptionRender={() => {
              return false
            }}
            rowSelection={{
              selectedRowKeys: drawerSelectGoods.map(i => i.id),
              onChange: (keys, rows) => {
                let tempList = [...rows, ...drawerSelectGoods.filter(i => !keys.includes(i.id))]
                if (cancelRowKeys.length) {
                  setDrawerSelectGoods(tempList.filter(i => !cancelRowKeys.includes(i.id)))
                } else {
                  setDrawerSelectGoods(tempList)
                }
              },

              onSelect: (record, selected) => {
                if (!selected) {
                  cancelRowKeys = [record.id]
                }
              }
            }}
            request={async params => {
              const param = {
                page: params.current,
                page_size: params.pageSize,
                plt: currentTab,
                get_online_goods: 1,
                is_display: params.is_display,
                merchant_id: params.merchant_id,
                goods_name: params.goods_name,
                merchant_id: params.merchant_id,
                id: params.id
              }

              const res = await GetPlatformGoodsList(param)
              getShopList()
              setAddGoodsPageSize(params.pageSize)
              // setDrawerSelectGoods([])
              return {
                data: res.data,
                success: true,
                total: res.total
              }
            }}
            pagination={{
              pageSize: addGoodsPageSize
            }}
            options={false}
            rowKey='id'
            scroll={{ x: 'max-content' }}
            columns={selectGoodsColumns}
          />
        </div>
      </Drawer>

      {/* <div>
        <Typography>
          <pre>{JSON.stringify(goodsList, null, 2)}</pre>
        </Typography>
      </div> */}
    </div>
  )
}

export default forwardRef(GoodsRecommendCom)
